import { getFiltersList } from "@/api/designer/filters";
import rescf from "../../composables/rescf";
import Tool from "@/utils/tool";
import { Session } from "@/utils/storage";

const app = {
  namespaced: true,
  state: {
    count: 0,
    formSearchData: {},
    filters: {},
    filtersTree: [],
    keepAlive: [],
    collapse: false,
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    appSFormData(state, val) {
      state.formSearchData[val.key] = val.val;
    },
    clearSFormData(state, key) {
      delete state.formSearchData[key];
    },
    async getAllFilters(state, key) {
      if (Session.get("__filters__")) {
        state.filters = JSON.parse(Session.get("__filters__"));
        state.filtersTree = JSON.parse(Session.get("__filters_tree__"));
      } else {
        const { code, data } = await getFiltersList();
        if (code === rescf.codeVal) {
          let tree = Tool.arrayToTree(data, 0);
          tree = Tool.compare(tree, "sort");
          let treeObj = {};
          tree.forEach((a) => {
            const d = Tool.toObject(a).d;
            treeObj[Object.keys(d)[0]] = Object.values(d)[0];
          });
          state.filters = treeObj;
          state.filtersTree = tree;
          Session.set("__filters__", JSON.stringify(treeObj));
          Session.set("__filters_tree__", JSON.stringify(tree));
        }
      }
    },
    setKeepAlive(state, val) {
      state.keepAlive = val;
    },
    setCollapse(state, val) {
      state.collapse = val;
    },
  },
  actions: {
    incrementIfOddOnRootSum({ commit, rootState }) {
      console.log("rootState", rootState.app.count);
      commit("increment");
    },
    setFormSearchData({ commit }, val) {
      commit("appSFormData", val);
    },
    clearFormSearchData({ commit }, key) {
      commit("clearSFormData", key);
    },
    getAllFilters({ commit }) {
      commit("getAllFilters");
    },
    refetchAllFilters({ commit }) {
      Session.remove("__filters__");
      console.log('__filters__')
      commit("getAllFilters");
    },
    setKeepAlive({ commit }, val) {
      commit("setKeepAlive", val);
    },
    setCollapse({ commit }, val) {
      commit("setCollapse", val);
    },
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    },
  },
};

export default app;
